<template>
  <el-form
    @keyup.enter.native.prevent="submitForm('ruleForm')"
    :model="ruleForm"
    :rules="rules"
    ref="ruleForm"
    label-position="left"
    label-width="0px"
    class="login-container">
    <h3 class="title">后台系统登录</h3>

    <el-form-item
      prop="username">
      <el-input
        type="text"
        v-model="ruleForm.username"
        auto-complete="off"
        placeholder="手机号码/代理编号/员工编号"></el-input>
    </el-form-item>
    <el-form-item
      prop="password">
      <el-input
        type="password"
        v-model="ruleForm.password"
        auto-complete="off"
        placeholder="密码"></el-input>
    </el-form-item>
    <el-form-item prop="captchaCode">
      <el-input
        type="text"
        v-model="ruleForm.captchaCode"
        auto-complete="off"
        placeholder="请输入图像验证码"></el-input>
    </el-form-item>

    <el-checkbox
      v-model="checked"
      checked
      class="remember">
      记住密码
    </el-checkbox>
    <a @click="fetchCaptcha" class="captcha-img" v-loading="loading"><img :src="captchaSrc"></a>

    <el-form-item
      style="width:100%;">
      <el-button
        type="primary"
        style="width:100%;"
        @click.native.prevent="submitForm('ruleForm')"
        :loading="logining">
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  //http://element.eleme.io/#/zh-CN/component/alert
  import {requestLogin, createCaptcha} from '../api/user';
  import {TOKEN_OBJ_ID} from '../common/tools';

  const CLIENT_SECRET = 'ONjIiDAupLsvWRgLc69guRIPv49RdWbFN44CKRiE';
  const CLIENT_ID = 6;
  const GRANT_TYPE = 'password';
  const SCOPE = '';
  export default {
    data() {
      return {
        logining: false,
        loading: false,
        checked: true,
        captchaSrc: '',
        ruleForm: {
          grant_type: GRANT_TYPE,
          client_id: CLIENT_ID,
          client_secret: CLIENT_SECRET,
          scope: SCOPE,
          username: 'admin',//电话号码 15527918920
          password: '123456', //密码:123456
          captchaId: '',//验证码的唯一id
          captchaCode: '',//图像验证码的字符
        },
        //https://github.com/yiminghe/async-validator
        rules: {
          username: [
            {
              required: true,
              message: '手机号码是必填',
              trigger: 'blur'
            },
//            {
//              type: 'string',
//              pattern: /^1[3|4|5|7|8][0-9]\d{4,8}$/,
//              message: '请输入正确手机号码',
//              trigger: 'blur'
//            }
          ],
          password: [
            {
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 6,
              message: '密码最短6位',
              trigger: 'blur'
            }
          ],
          captchaCode: [
            {
              required: true,
              message: '请输入图像验证码',
              trigger: 'blur'
            },
            {
              type: 'string',
              pattern: /^\d{5}$/,
              message: '请输入5位数的数字',
              trigger: 'blur'
            }
          ]
        },
      };
    },
    methods: {

      submitForm(formName) {
        //https://cn.vuejs.org/v2/guide/components.html#子组件索引
        this.$refs[formName].validate(valid => {
          if (valid) {
            requestLogin(this.ruleForm).then(res => {
              if (res.msg) {
                this.$notify({
                  title: '验证码错误',
                  message: '请重新输入验证码',
                  type: 'error'
                });
              } else {
                if (this.checked) {
                  localStorage.setItem(TOKEN_OBJ_ID, JSON.stringify(res));
                } else {
                  sessionStorage.setItem(TOKEN_OBJ_ID, JSON.stringify(res));
                }
              }
              this.$router.push({path: '/'});
            }).catch(error => this.ezNotifyAxiosCatch(error))
          }
        });
      },
      //获取验证码  点击验证码刷新的时候 调用这个方法
      fetchCaptcha() {
        this.loading = true;
        let uniqueId = new Date().valueOf();
        createCaptcha({captchaId: uniqueId}).then(res => {
          this.captchaSrc = res.data;
          this.ruleForm.captchaId = uniqueId
          this.loading = false;
        }).catch(error => this.ezNotifyAxiosCatch(error));
      }
    },
    //获取图形码
    mounted() {
      this.fetchCaptcha();
    },
    created() {
      let token = this.$route.query.access_token;
      if (token) {
        let temp = JSON.parse('{"token_type":"Bearer","expires_in":31536000,"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjQ1ZTZiZGJmNDdhMTAxYjliMThlMmZlYjAwN2FmNjEzYmM0NDhjMzlmZjJmNjFjMWFjOTUwZjMyYmRjZTUxMjVmZGZhNmQ4YWRjNDEzMmEzIn0.eyJhdWQiOiI2IiwianRpIjoiNDVlNmJkYmY0N2ExMDFiOWIxOGUyZmViMDA3YWY2MTNiYzQ0OGMzOWZmMmY2MWMxYWM5NTBmMzJiZGNlNTEyNWZkZmE2ZDhhZGM0MTMyYTMiLCJpYXQiOjE1MTEwMDIzMjQsIm5iZiI6MTUxMTAwMjMyNCwiZXhwIjoxNTQyNTM4MzI0LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.ZprqZBXN8Sj0W1frif5oC0v0ezfUxuN4EhlGTdrY6JwPXyJ0SeJ_0cJWsQrgE4VEYYmgMFpEQZkvzMLjh3u_DeEgmCdXPHYinwFQE2chOwD9ccIyngpvSEU_BeXdWv_VdLZv7TPYRY-SjuCpT_FVApfObcBUmumZZP6e8ILlMZE0eX50XHaY98XzfdBnQQRsxeKumsm8u8vNGezA2aLuKzjWkonocCeZa7o6UWNdsxKHa4sW0U0ZB8roo-yqF9F8g3mPPA3VDdwzNpbvQ8uTBiQuimLRaW0j7Cog4Fs1Xo_lrTaVI_meF4vF7zR4w4e86FewzRJXG5oyxGnFbLEeHoxRi8Re7kSY4jLT2SmXCAwLLUizrne07yzTTPAu_aP_q3Q3Oncf400n064_VsT3rmZQsuc8hFd2v3MqA9G_n4J5gdEQD4n3u1Z8yQAtVgJx_L45lJFv-FKR4wV6ARpOFv75BgIasMHEqLNs8nRewz2y2B_XFKU4aT9__c9-F677Z34pPyWveGBf-ssjEN561Pfi5kyYA8diXGBy5uFELHBsejgn_WAhuLdyhyIMiP8-Y98miYFcQAdtXZ1tTtFDwp5wNa35GzrisEEuVcPYl7T89vBbwqbDFG3LQVoBfPgE1FJ0CDjk_F2y7slmaepUEPlXNucl690q7zWvwfV7w-o","refresh_token":"def5020008074e8dcbbe90f31b0e46a5b240af4090b4da26462cf20d39cff3cb5c064f26bc18c7a6d083b3d08856087cc78af9d6425f9f1de4680f17f2346a2320dd23d089df2c579363a2164e9fc82c05e9500b725475008d85bc4ff0175cab09e4b798941722a6bd719365bf4ca74cc0fc6321c99386e3f8231f01cf8eb4152855b69f4f150c52a3037bd809a4a9d423be5e28304f51520ec5c663711e1780919f89eab7f4fe12b128ac219891c45d0650dcd5e6e816d2b8701028e57eb848446cc733ee9a3c34f3022a8f054498396388e2d8135452855b2a6071fc9fb660faf19a1fbd64cbd7e5e6f2e07c9990110e150febe99f8036b790578ac1b79731066b72c58f47d045290044728ca2230865dee99f4d67a3049777751e8c969547e5912f2277293aa96d006f7dfa8b08bd4513c4e409de4b25297914a2c1874ef30c3af51a44e265b26a78c7e5240ddf733e8ed0c50e5bec1d8626592af89bea"}');
        temp.access_token = token;
        localStorage.clear()
        sessionStorage.clear()
        let someString = JSON.stringify(temp);
        sessionStorage.setItem(TOKEN_OBJ_ID, someString);
        localStorage.setItem(TOKEN_OBJ_ID, someString);
        this.$router.replace('/');
      }
    },
  }

</script>

<style scoped>

  .login-container {
    /*box-shadow: 0 0px 8px 0 rgba(0, 0, 0, 0.06), 0 1px 0px 0 rgba(0, 0, 0, 0.02);*/
    -webkit-border-radius: 5px;
    border-radius: 5px;
    -moz-border-radius: 5px;
    background-clip: padding-box;
    margin: 70px auto auto auto;
    width: 350px;
    padding: 35px 35px 15px 35px;
    background: #fff;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;

  }

  .title {
    margin: 0px auto 40px auto;
    text-align: center;
    color: #505458;
  }

  .remember {
    margin: 0px 0px 35px 0px;
  }

  .captcha-img {
    position: relative;
    float: right;
    width: 150px;
    height: 40px;
  }

  .captcha-img:hover {
    cursor: pointer;
  }

</style>
